package com.gourd.common.utils;

import com.gourd.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author gourd
 * @description
 * @date 2018/10/26 10:20
 **/
@Slf4j
@Component
@RefreshScope
public class IdGeneratorUtil {

    @Value("${idWorker.workerId}")
    private  Integer workerId;

    @Value("${idWorker.dataCenterId}")
    private  Integer dataCenterId;

    /**
     * 获取一个id
     * @return
     */
    public Long getSeqId(){
        IdWorker idWorker = new IdWorker(workerId,dataCenterId);
        return idWorker.nextId();
    }

    /**
     * 获取num个id
     * @return
     */
    public Set<Long> getSeqIds(int num){
        Set<Long> ids = new HashSet<>();
        if(num>0){
            IdWorker idWorker = new IdWorker(workerId,dataCenterId);
            for(int i=0; i<num;i++){
                ids.add(idWorker.nextId());
            }
        }else {
            throw new ServiceException("获取id的num需大于0");
        }
        return ids;
    }
}
